package com.lql.cart.listener;

import com.hmall.common.utils.UserContext;
import com.lql.cart.service.ICartService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RequiredArgsConstructor
public class CartCleanListener {
    private final ICartService cartService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "cart.clear.queue", durable = "true"),
            exchange = @Exchange(value = "trade.topic", type = ExchangeTypes.TOPIC),
            key = "order.create"
    ))
    public void listenerClearSuccess(List<Long> ids, Message message) {
        Long userInfo = message.getMessageProperties().getHeader("userInfo");
        // 设置用户信息
        UserContext.setUser(userInfo);
        cartService.removeByItemIds(ids);
        // 业务完成，清理用户信息
        UserContext.removeUser();
    }
}
